package com.hp.bon.sgw.wh.processor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.convert.DataExchangerImpl;
import com.hp.bon.sgw.convert.Xml2AVPConvetor;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.ChannelServer;
import com.hp.bon.sgw.core.InprogressMessageQueue;
import com.hp.bon.sgw.core.processor.Processor;
import com.hp.bon.sgw.core.route.RouteInfo;
import com.hp.bon.sgw.domain.ConvMapInfo;
import com.hp.bon.sgw.util.Comutils;
import com.hp.bon.sgw.util.dcc.DccAvpHelper;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.util.DateUtil;
import com.hp.ocs.diameter.message.AVP;
import com.hp.ocs.diameter.message.Message;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.hp.bon.sgw.Constants.LOG;

public class UserResourceDccProcessor extends Processor{
	private static ConcurrentHashMap<String, String> productOfferIdMap = new ConcurrentHashMap<String, String>();
    private static final Logger logger = LoggerFactory.getLogger(FlowDccProcessor.class);
	
	private long time=1000L;
	
	private static ConcurrentHashMap<String, Integer> countMap = new ConcurrentHashMap<String, Integer>();
	
	private UserResourceConfigService userResourceConfigService ;
	
	private static DataExchangerImpl instance;
	
	private static String PRODUCT_OFFER_ID = "";
	
	private static final int WEBSERVICER = 1;
	
	private static String QUERY_FLAG = "";
	
	private static String QUERY_TYPE = "";
    private JSONObject jsonObject =new JSONObject();
	
	public UserResourceConfigService getUserResourceConfigService() {
		return userResourceConfigService;
	}
	//增加开关配置，jf3_flag=1，当该值配置为1，则表示不走鉴权，直接全部调用云平台； jf3_flag=0，则还是按目前流程走；
		private static	String jf3_flag="";
	public void setUserResourceConfigService(
			UserResourceConfigService userResourceConfigService) {
		this.userResourceConfigService = userResourceConfigService;
	}

	public void shutdown() {
		dccProcessor.interrupt();
	}
	DccProcessor dccProcessor;
	public void init(){
		dccProcessor=new DccProcessor();
		dccProcessor.start();
	}
	
	public static DataExchangerImpl getInstance() {
		if (instance == null) {
			instance = new DataExchangerImpl();
		}
		return instance;
	}
	
	class DccProcessor extends Thread{

		@Override
		public void run() {
			while (true) {
				try {
					time=userResourceConfigService.getLongValue("limit_config_time", 1000L);
					countMap.clear();
					logger.info("clear UsageMap time:"+time);
					sleep(time);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		}
		
	}

	public  synchronized Integer putValue(String key) {
		Integer i =countMap.get(key);
		logger.info("asd:"+i);
		if (i==null) {
			countMap.put(key, 1);
			i = 1;
		}else{
			i++;
			countMap.put(key,i);
		}
		return i;
	}
	@Override
	public int process(CallParam callParam) {
		jf3_flag = userResourceConfigService.getValue("jf3_flag","");
        String jf3_ratable_flag = userResourceConfigService.getValue("jf3_ratable_flag","");

		logger.info("===========UserResourceDccProcessor.process===============" );
		XmlMessage request = (XmlMessage) callParam.getRequest();
		String accNbr = "";
		String destinationAttr = "";
		String billingCycle = "";
		Document root;
		try {
			root = DocumentHelper.parseText(request.getDATA());
			org.dom4j.Node node = root.selectSingleNode("//Service_Information/Bill_Information/Acc_Nbr");
			if (node != null) {
				accNbr = node.getStringValue();
			}
			
			node = root.selectSingleNode("//Service_Information/Bill_Information/Billing_Cycle");
			if (node != null) {
				billingCycle = node.getStringValue();
			}
			
			node = root.selectSingleNode("//Service_Information/Bill_Information/DestinationAttr");
			if (node != null) {	
				destinationAttr = node.getStringValue();
			}
			node = root.selectSingleNode("//Service_Information/Bill_Information/DestinationAttr");
			if (node != null) {
				destinationAttr = node.getStringValue();
			}
			node = root.selectSingleNode("//Service_Information/Bill_Information/Product_Offer_Id");
			if (node != null) {
				PRODUCT_OFFER_ID = node.getStringValue();
			}
			node = root.selectSingleNode("//Service_Information/Bill_Information/Query_Flag");
			if (node != null) {
				QUERY_FLAG = node.getStringValue();
			}
			node = root.selectSingleNode("//Service_Information/Bill_Information/QueryType");
			if (node != null) {
				QUERY_TYPE = node.getStringValue();
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		JSONObject operAttrStruct=new JSONObject();
        operAttrStruct.put("operServiceId", DateUtil.dateTimeToStr(new Date())+(int)(Math.random()*1000000) );
        operAttrStruct.put("lanId","8420000");
        operAttrStruct.put("operPost","1");
        operAttrStruct.put("operOrgId","1");
        operAttrStruct.put("staffId","1");
        operAttrStruct.put("operTime",DateUtil.dateTimeToStr(new Date()));
        jsonObject.put("destinationAttr",destinationAttr);
        jsonObject.put("operAttrStruct",operAttrStruct);
        jsonObject.put("accNbr",accNbr);
        jsonObject.put("billingCycle",billingCycle);
        jsonObject.put("offerId",PRODUCT_OFFER_ID);

		StringBuilder sb = new StringBuilder();
		sb.append("<Service_Information>")
			.append("<Bill_Information>") ;

		if(accNbr != null && !"".equals(accNbr)){
			sb.append("<Acc_Nbr>").append(accNbr).append("</Acc_Nbr>");
		}
		if(destinationAttr != null && !"".equals(destinationAttr)){
			sb.append("<DestinationAttr>").append(destinationAttr).append("</DestinationAttr>");
		}
		if(billingCycle != null && !"".equals(billingCycle)){
			sb.append("<Billing_Cycle>").append(billingCycle).append("</Billing_Cycle>");
		}
		sb.append("</Bill_Information>").append("</Service_Information>");

		//改造开始2019-10-23
        logger.info("===========jf3_ratable_flag==============="+jf3_ratable_flag );
		if( "1".equals(jf3_ratable_flag)) {
            logger.info("=========== 进入新流程===============");
			StringBuilder sb2 = new StringBuilder();
			getWebService(accNbr, billingCycle, destinationAttr, sb2);
			logger.info("===========进入webservice==============="+sb2 );
			String resp = StringEscapeUtils.unescapeXml(sendWebSevice2(callParam, sb2));
			try {
				XmlMessage ack = new XmlMessage(false);
				logger.info("===========进入CCA==============="+resp);
				sendCCAToOutNet2(callParam, resp, ack);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return 0;
		}
        logger.info("=========== 进入老程序===============");
		this.sendReqMsg(callParam, sb.toString() ,"1" ,"RatableAuth.HSS@027.ctnbc-bon.net");
		return 0;
	}
    
    private CallParam sendReqMsg(CallParam callParam ,String data ,String sendCount ,String sci)	
    {
		String sessionId2 = callParam.getSessionId()+"A";
		XmlMessage req = new XmlMessage(true);
		req.setDATA(data);
		try {
			req.setDataElement(Comutils.parseText(data).getRootElement());
		} catch (Exception e) {
			e.printStackTrace();
		}
		req.setMID(sessionId2);
		req.setUID(callParam.getUserName());
		req.setSCID(sci);
		CallParam newCallParam = new CallParam(sessionId2, sci, req, callParam.getUserName(), callParam.getAsynHandler());
		newCallParam.setBussinessCallId(callParam.getBussinessCallId());
		newCallParam.setFromNode(callParam.getFromNode());
		newCallParam.setProcessor(this);
		RouteInfo r = ChannelServer.findRoute(newCallParam.getServiceContextId());
		int ret = 0;
		String errMsg = null;
		if (r == null) {
			errMsg = "No Route for " + newCallParam.getServiceContextId();
			ret = 3002;// 没有查到路由
		} else if (r.result != 0) {
			errMsg = "Route unavailable for " + newCallParam.getServiceContextId();
			ret = r.result;
		}
		if (ret != 0) {
			newCallParam.setRetCode(3002);
			newCallParam.setResultMsg(errMsg);
			callParam.getAsynHandler().onCallResult(newCallParam);
			return newCallParam;
		}
		newCallParam.setToNode(r.curNode);
		InprogressMessageQueue.getInstance().addRequest(newCallParam);
		r.curNode.getChannel().sendRequest(newCallParam);
		return newCallParam;
	}
	
	@Override
	public int endProcess(CallParam callParam) {
		logger.info("===========UserResourceDccProcessor.endProcess===============" );
		logger.info("callParam.getRetCode():"+callParam.getRetCode());
		if(callParam.getRetCode()!=Constants.DIAMETER_SERVICE_RESULT_SUCCESS){
			if(callParam.getRetCode()==userResourceConfigService.getIntValue("DIAMETER_RESULT_TOO_BUSY", 2005)){
				callParam.getAsynHandler().onCallResult(callParam);
				return 0 ;
			}
		}
		int webService = userResourceConfigService.getIntValue("IS_WEBSERVICE", 0);
		XmlMessage request = (XmlMessage) callParam.getRequest();
		String accNbr="" ,billingCycle="" ,destinationAttr="";
		AVP avp = null;
		Document root;
		try {
			root = DocumentHelper.parseText(request.getDATA());
			org.dom4j.Node node = root.selectSingleNode("//Service_Information/Bill_Information/Acc_Nbr");
			if (node != null) {
				accNbr = node.getStringValue();
			}
			
			node = root.selectSingleNode("//Service_Information/Bill_Information/Billing_Cycle");
			if (node != null) {
				billingCycle = node.getStringValue();
			}
			
			node = root.selectSingleNode("//Service_Information/Bill_Information/DestinationAttr");
			if (node != null) {
				destinationAttr = node.getStringValue();
			}
			node = root.selectSingleNode("//Service_Information/Bill_Information/DestinationAttr");
			if (node != null) {
				destinationAttr = node.getStringValue();
			}
		} catch (DocumentException e1) {
			e1.printStackTrace();
		}
		StringBuilder sb = new StringBuilder();
		String sci = callParam.getServiceContextId();
		Map<String, ConvMapInfo> allAVPMap = Xml2AVPConvetor.getInstance().getALLNamesMap();
		Message RatableAuthResponse = (Message) callParam.getRecvResponse();
		String isHbFlag = DccAvpHelper.getAVPValue(RatableAuthResponse, "Service_Information/Auth_Group/is_hb_flag", allAVPMap);
		isHbFlag = isHbFlag == null ? "" : isHbFlag;
		String homeAreaCode = DccAvpHelper.getAVPValue(RatableAuthResponse, "Service_Information/Auth_Group/HomeAreaCode", allAVPMap);
		homeAreaCode = homeAreaCode == null ? "" :homeAreaCode;
		if(webService == WEBSERVICER && isHbFlag.equals("1")) {
			getWebService(accNbr, billingCycle, destinationAttr, sb);
			
		} else {
			getDCC(callParam, accNbr, billingCycle, destinationAttr, sb);
		}
		if("".equals(isHbFlag) || "".equals(homeAreaCode)){
			callParam.getAsynHandler().onCallResult(parseResponse(callParam));
			return 0 ;
		}
		
		if (sci.equals("UserResourceQuery.ABMWH@027.ctnbc-bon.net")
				|| sci.equals("UserResourceQuery.ABMHB@027.ctnbc-bon.net")
				|| sci.equals("UserResourceQuery.ABM@027.ctnbc-bon.net")) {
			callParam.getAsynHandler().onCallResult(parseResponse(callParam));
		}
		if(sci.equals("RatableAuth.HSS@027.ctnbc-bon.net")){//预后判断
			if(webService == WEBSERVICER && isHbFlag.equals("1")) {
				logger.info("===========进入webservice==============="+sb );
				String resp = StringEscapeUtils.unescapeXml(sendWebSevice(callParam, sb));
				try {
					XmlMessage ack = new XmlMessage(false);
					logger.info("===========进入CCA==============="+resp);
					sendCCAToOutNet(callParam, resp, ack);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else {
				if(isHbFlag.equals("1") && homeAreaCode.equals("1001")){
					this.sendReqMsg(callParam, sb.toString() ,"2" ,"UserResourceQuery.ABMWH@027.ctnbc-bon.net");
				} else if(isHbFlag.equals("1") && !homeAreaCode.equals("1001")){
					this.sendReqMsg(callParam, sb.toString() ,"2" ,"UserResourceQuery.ABMHB@027.ctnbc-bon.net");
				}else{
					this.sendReqMsg(callParam, sb.toString() ,"2" ,"UserResourceQuery.ABM@027.ctnbc-bon.net");
				}
			}
			
		}
		return 0;
	}
	
	public CallParam parseResponse(CallParam callParam) {
		Message request = (Message) callParam.getRecvResponse();
		Message answer = new Message();
		answer.prepareResponse(request);
		String sessionId = callParam.getSessionId();
		sessionId = sessionId.substring(0,sessionId.length()-2);
		request.updateAVP_UTF8String("263", sessionId);
		CallParam newcallParam = changeAVPTOXMl(callParam, request, sessionId);
		return newcallParam;
	}

	private CallParam changeAVPTOXMl(CallParam callParam, Message request,String sessionId) {
		CallParam newcallParam = new CallParam(sessionId, callParam.getServiceContextId(), request, callParam.getUserName(), callParam.getAsynHandler());
		XmlMessage ack = new XmlMessage(false);
		XmlMessage message = (XmlMessage)callParam.getRequest();
		Message messageRequset = (Message)newcallParam.getRequest();
		ack.setMID(message.getMID());
		ack.setREPTAG(0);
		ack.setSIG(null);
		ack.setRC("0");
		ack.setDS("SUCCESS");
		ack.setDATA(request.getDictionary().toString());
		newcallParam.setRecvResponse(callParam.getRecvResponse());
		newcallParam.setRequest(callParam.getRequest());
		ack = BuzProcessorManager.getInstance().convertMessageToAck(newcallParam);
		newcallParam.setRequest(messageRequset);
		newcallParam.setFromNode(callParam.getFromNode());
		newcallParam.setRecvResponse(ack);
		newcallParam.setResponse(null);
		return newcallParam;
	}
	public int proccessResponse(CallParam callParam) {
		callParam.getAsynHandler().onCallResult(callParam);
		return 0;
	}
	private String sendWebSevice(CallParam callParam, StringBuilder sb) {
		String resp = "";
	    String url  = userResourceConfigService.getValue("RATABLE_RESOURCE_QUERY_URL","");
		PostMethod post = new PostMethod(url);
		try {
			RequestEntity requestEntity = new StringRequestEntity(sb.toString(), "text/xml", "UTF-8");
			post.setRequestEntity(requestEntity);
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5*1000);
			try {
				client.executeMethod(post);
			} catch (HttpException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				logger.info("===========完成webservice==============="+resp);
				resp = post.getResponseBodyAsString();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return resp;
	}

    private String sendWebSevice2(CallParam callParam, StringBuilder sb) {
        String resp = "";
        String url  = userResourceConfigService.getValue("RATABLE_RESOURCE_QUERY_URLjf3","");
        PostMethod post = new PostMethod(url);
        logger.info("=========== http请求开始===============url:"+url);
        try {
            RequestEntity requestEntity = new StringRequestEntity(jsonObject.toString(), "application/json", "UTF-8");
            post.setRequestEntity(requestEntity);
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5*1000);
            try {
                client.executeMethod(post);
            } catch (HttpException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                logger.info("===========完成 http请求==============="+resp);
                resp = post.getResponseBodyAsString();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return resp;
    }

	private void getDCC(CallParam callParam, String accNbr, String billingCycle, String destinationAttr, StringBuilder sb) {
		sb.append("<Service_Information>").append("<Bill_Information>");

		if(accNbr != null && !"".equals(accNbr)){
			sb.append("<Acc_Nbr>").append(accNbr).append("</Acc_Nbr>");
		}
		if(billingCycle != null && !"".equals(billingCycle)){
			sb.append("<Billing_Cycle>").append(billingCycle).append("</Billing_Cycle>");
		}
		if(destinationAttr != null && !"".equals(destinationAttr)){
			sb.append("<DestinationAttr>").append(destinationAttr).append("</DestinationAttr>");
		}
		LOG.debug("2"+callParam.getSessionId());
		if (productOfferIdMap.get(callParam.getSessionId()) != null && !"".equals(productOfferIdMap.get(callParam.getSessionId()))) {
			sb.append("<Product_Offer_Id>").append(productOfferIdMap.get(callParam.getSessionId())).append("</Product_Offer_Id>");
			productOfferIdMap.remove(callParam.getSessionId());
		}
			
		sb.append("</Bill_Information>").append("</Service_Information>");
	}

	private void getWebService(String accNbr, String billingCycle, String destinationAttr, StringBuilder sb) {
		sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.hquery.ailk.com/\">");
		sb.append("<soapenv:Header/>");
		sb.append("<soapenv:Body>");
		sb.append("<ser1:queryRatable xmlns:ser1=\"http://server.ratable.asiainfo.com/\">");
		sb.append("<param><![CDATA[  ");
		sb.append("<query from='" +212+ "'>");
		if(accNbr != null && !"".equals(accNbr)){ 
			sb.append("<AccNbr>" + accNbr + "</AccNbr>");
		}
		if(destinationAttr != null && !"".equals(destinationAttr)){
			sb.append("<DestinationAttr>" + destinationAttr + "</DestinationAttr>");
		}
		if(billingCycle != null && !"".equals(billingCycle)){
			sb.append("<BillingCycle>" + billingCycle + "</BillingCycle>");
		}
		sb.append("<ProductOfferId>" + PRODUCT_OFFER_ID + "</ProductOfferId>");
		sb.append("</query>");
		sb.append("]]>");
		sb.append("</param>");
		sb.append("</ser1:queryRatable>");
		sb.append("</soapenv:Body>");
		sb.append("</soapenv:Envelope>");
	}

	private void sendCCAToOutNet(CallParam callParam, String resp,XmlMessage ack) throws Exception {
		Document root = null;
		String beginTime = "";
		String endTime = "";
		SimpleDateFormat format =  new SimpleDateFormat("yyyyMMddHHmmss"); 
		try {
			root = DocumentHelper.parseText(resp);
			List<Element> nodes=root.selectNodes("//RespondRatableQuery");
			for (Element node : nodes) {
				Element e=(Element)node;
				Element beginTimeElement=e.element("BeginTime");
				beginTime = beginTimeElement.getStringValue();
				Date beginTimeStrDate=format.parse(beginTime);
				beginTimeElement.setText(beginTimeStrDate.toString());
				Element endTimeElement=e.element("EndTime");
				endTime = endTimeElement.getStringValue();
				Date endTimeStrDate=format.parse(endTime);
				endTimeElement.setText(endTimeStrDate.toString());
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		resp = root.asXML();
		String  respStr = "<ServiceInformation>(.*)</ServiceInformation>";
		Pattern pattern = Pattern.compile(respStr);
		Matcher matcher = pattern.matcher(resp);
		String interceptRespStr = "";
		
		while (matcher.find()) {
			interceptRespStr = matcher.group(1);
		}
		resp = "<ServiceInformation>"+interceptRespStr+"</ServiceInformation>";
		resp = resp.replaceAll("ServiceInformation", "Service_Information");
		resp = resp.replaceAll("ServiceResultCode", "Result");
		resp = resp.replaceAll("ParaFieldResult", "Para_Field_Result");
		resp = resp.replaceAll("ProductOFFinfo", "Product_OFF_info");
		resp = resp.replaceAll("ProductOfferId", "Product_Offer_Id");
		resp = resp.replaceAll("ProdOfferInstanceId", "ProdOfferInstanceId");
		resp = resp.replaceAll("ProductOFFName", "Product_OFF_Name");
		resp = resp.replaceAll("OfferType", "Offer-Type");
		resp = resp.replaceAll("RespondRatableQuery", "Respond_Ratable_Query");
		resp = resp.replaceAll("OwnerType", "Owner_Type");
		resp = resp.replaceAll("OwnerID", "Owner_ID");
		resp = resp.replaceAll("RatableResourceID", "Ratable_Resource_ID");
		resp = resp.replaceAll("RatableResourcename", "Ratable_Resource_name");
		resp = resp.replaceAll("BeginTime", "BeginTime");
		resp = resp.replaceAll("EndTime", "End_Time");
		resp = resp.replaceAll("RatableAmount", "Ratable_Amount");
		resp = resp.replaceAll("BalanceAmount", "Balance_Amount");
		resp = resp.replaceAll("UsageAmount", "Usage-Amount");
		resp = resp.replaceAll("UnitTypeId", "UnitType_Id");

        LOG.info("==================返回CCA  resp=============="+resp);
		if(!resp.isEmpty()) {
			XmlMessage message = (XmlMessage)callParam.getRequest();
			String mid = message.getMID();
			ack.setMID(mid.substring(0, mid.length()-1));
			ack.setREPTAG(0);
			ack.setRTT(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Long.valueOf(System.currentTimeMillis())));
			ack.setSIG(null);
			ack.setRC("0");
			ack.setDS("SUCCESS");
			ack.setDATA(resp);
			callParam.setRecvResponse(ack);
		}
		callParam.setRequest(callParam.getSendRequest());
		callParam.getAsynHandler().onCallResult(callParam);
	}
    private void sendCCAToOutNet2(CallParam callParam, String resp,XmlMessage ack) throws Exception {
        JSONObject resp_json=JSONObject.parseObject(resp);
        Element serviceInformation = DocumentHelper.createElement("Service_Information");
        Element element = serviceInformation.addElement("Result");
        element.setText(resp_json.getString("resultCode"));
        element = serviceInformation.addElement("Para_Field_Result");
        element.setText(resp_json.getString("resultMsg"));
        JSONArray offerInstInfoList=resp_json.getJSONArray("offerInstInfo");
        if(offerInstInfoList != null && !offerInstInfoList.isEmpty()){
            for (int i=0;i<offerInstInfoList.size();i++){
                JSONObject offer=offerInstInfoList.getJSONObject(i);
                serviceInformation.addElement("Product_OFF_info");//添加空节点
                List<Element> list =serviceInformation.elements("Product_OFF_info");
                Element offerInstInfo = list.get(i);
                offerInstInfo.addElement("Product_Offer_Id").setText(offer.getString("offerId"));
                offerInstInfo.addElement("Product_OFF_Name").setText(offer.getString("offerName"));
                offerInstInfo.addElement("Offer-Type").setText(offer.getString("offerType"));
                offerInstInfo.addElement("ProdOfferInstanceId").setText(offer.getString("offerInstId"));
                JSONArray AccuQryListS=offer.getJSONArray("AccuQryList");
                if(AccuQryListS != null && !AccuQryListS.isEmpty()){
                    for (int j=0;j<AccuQryListS.size();j++){
                        offerInstInfo.addElement("Respond_Ratable_Query");//添加空节点
                        JSONObject AccuQry=AccuQryListS.getJSONObject(j);
                        List<Element> list2= offerInstInfo.elements("Respond_Ratable_Query");
                        Element AccuQryList= list2.get(j);
                        AccuQryList.addElement("Owner_Type").setText(AccuQry.getString("ownerType"));
                        AccuQryList.addElement("Owner_ID").setText(AccuQry.getString("ownerId"));
                        AccuQryList.addElement("Ratable_Resource_ID").setText(AccuQry.getString("accuTypeAttr"));
                        AccuQryList.addElement("Ratable_Resource_name").setText(AccuQry.getString("accuTypeName"));
                        AccuQryList.addElement("BeginTime").setText(new SimpleDateFormat("yyyyMMddHHmmss").parse(AccuQry.getString("beginTime")).toString());
                        AccuQryList.addElement("End_Time").setText(new SimpleDateFormat("yyyyMMddHHmmss").parse(AccuQry.getString("endTime")).toString());
                        AccuQryList.addElement("Ratable_Amount").setText(AccuQry.getString("initVal"));
                        AccuQryList.addElement("Balance_Amount").setText(AccuQry.getString("accuVal"));
                        AccuQryList.addElement("Usage-Amount").setText(AccuQry.getString("usageVal"));
                        AccuQryList.addElement("UnitType_Id").setText(AccuQry.getString("unitTypeId"));
                    }
                }

            }
        }

        LOG.info("==================返回CCA  serviceInformation=============="+serviceInformation.asXML());
        if(!resp.isEmpty()) {
            XmlMessage message = (XmlMessage)callParam.getRequest();
            String mid = message.getMID();
            ack.setMID(mid);
            ack.setREPTAG(0);
            ack.setRTT(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Long.valueOf(System.currentTimeMillis())));
            ack.setSIG(null);
            ack.setRC("0");
            ack.setDS("SUCCESS");
            ack.setDATA(serviceInformation.asXML());
            callParam.setRecvResponse(ack);
        }
        callParam.setRequest(callParam.getSendRequest());
        callParam.getAsynHandler().onCallResult(callParam);
    }

    private  String getDate(String dateSe){
	    Date date;
	    try {
            date=   new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).parse(dateSe);
        }catch (Exception e){
            date=new Date();
        }
	    return new SimpleDateFormat("yyyyMMddHHmmss").format(date);
    }
	public static void main(String[] args) {

	}
}
